package com.jy.oms.framework.asyn.task.handler;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author liuquan
 */
public class MethodTaskHandler implements ITaskHandler {

    private final String taskCode;

    private final Object target;

    private final Method executeMethod;

    private final Method callbackMethod;

    public MethodTaskHandler(String taskCode, Object target, Method executeMethod, Method callbackMethod) {
        this.taskCode = taskCode;
        this.target = target;
        this.executeMethod = executeMethod;
        this.callbackMethod = callbackMethod;
    }

    @Override
    public Object executeTask(Object param) throws Throwable {
        MethodTaskHandlerThreadLocal.set(true);
        try {
            return executeMethod.invoke(target, param);
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        } catch (Exception e) {
            throw e;
        } finally {
            MethodTaskHandlerThreadLocal.clear();
        }
    }

    @Override
    public void executeTaskCallback(Object param, Object result) throws Throwable {
        if (callbackMethod != null) {
            callbackMethod.invoke(target, param, result);
        }
    }
}
